package cn.lopr.im.android.mvp.view.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import java.util.Map;

import cn.lopr.im.android.R;
import cn.lopr.im.android.bean.ArticleVo;
import cn.lopr.im.android.bean.PageInfo;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.common.app.Activity;
import cn.lopr.im.android.databinding.ActivityPersonalHomepageBinding;
import cn.lopr.im.android.mvp.contact.IPersonalHomepageContact;
import cn.lopr.im.android.mvp.presenter.PersonalHomepagePresenterImpl;
import cn.lopr.im.android.mvp.view.adapters.CommunityArticleAdapter;
import cn.lopr.im.android.mvp.view.dialog.BtnBottomDialog;

public class PersonalHomepageActivity extends Activity implements IPersonalHomepageContact.IPersonalHomepageView {
    private ActivityPersonalHomepageBinding binding;

    CommunityArticleAdapter communityArticleAdapter;
    private PersonalHomepagePresenterImpl personalHomepagePresenter;
    private String token;
    private int userId;
    private BtnBottomDialog btnBottomDialog;

    /**
     * 分页
     */
    private int page = 1;
    private int size = 2;
    private boolean isLastPage = false;
    /**
     * 监听是否滑到底部 会一直触发
     */
    private boolean over = false;

    @Override
    protected View getContentLayoutId() {
        binding = ActivityPersonalHomepageBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    protected void initData() {
        super.initData();
        token = this.getToken(this.getApplicationContext());
        userId = getIntent().getIntExtra("userId", -1);
        personalHomepagePresenter = new PersonalHomepagePresenterImpl(this);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        this.binding.ivBack.setOnClickListener(e -> this.finish());

        this.binding.swipeRefresh.setOnRefreshListener(() -> {
            this.page = 1;
            this.personalHomepagePresenter.getArticle(this.getToken(this.getApplicationContext()), userId, this.page, this.size);
            this.binding.swipeRefresh.setRefreshing(false);
        });
        this.binding.rlContainer.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem = 0;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.i("ddd", "onScrollStateChanged: " + newState + "end?: "
                        + recyclerView.canScrollVertically(1)
                        + " sor: " + recyclerView.getScrollState()
                        + " end: " + communityArticleAdapter.getItemCount());

                if (!recyclerView.canScrollVertically(1)) {
                    loadMore();
                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

    }

    private void loadMore() {
        if (isLastPage || over) {
            return;
        }
        over = true;
        page = page + 1;
        communityArticleAdapter.showLoading();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                personalHomepagePresenter.getArticle(getToken(getApplicationContext()), userId, page, size);
            }
        }.start();

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void getUserInfoSuccess(User user) {
        binding.tvNickname.setText(user.getNickname());
        binding.tvTel.setText("手机号：" + user.getPhone());
        binding.tvAutograph.setText("签名：" + user.getIntroduction());
        binding.tvTel.setText(user.getPhone());

        Glide.with(getApplicationContext()).load(user.getPortrait()).placeholder(R.drawable.default_head_portrait)
                .dontAnimate()
                .into(new SimpleTarget<GlideDrawable>() {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                        binding.ivPortrait.setImageDrawable(resource);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                        binding.ivPortrait.setImageDrawable(errorDrawable);
                    }
                });
    }

    @Override
    public void getArticleSuccess(PageInfo<ArticleVo> articleVos) {
        over = false;
        if (articleVos == null || articleVos.getList().size() == 0) {
            binding.tvHas.setVisibility(View.VISIBLE);
            binding.rlContainer.setVisibility(View.GONE);
            this.isLastPage = true;
        } else {
            binding.tvHas.setVisibility(View.GONE);
            binding.rlContainer.setVisibility(View.VISIBLE);
            this.isLastPage = articleVos.isIsLastPage();
        }

        if (this.communityArticleAdapter != null) {
            this.communityArticleAdapter.showLoadMore();
            this.communityArticleAdapter.refresh(articleVos, "");
        } else {
            this.communityArticleAdapter = new CommunityArticleAdapter(this.getApplicationContext(), articleVos);
            this.binding.rlContainer.setAdapter(this.communityArticleAdapter);
        }
        this.isLastPage = articleVos.isIsLastPage();

        this.communityArticleAdapter.onRecyclerViewItemClickListener(new CommunityArticleAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int section) {
                ArticleVo articleVo = (ArticleVo) view.getTag();
                Log.i("CommunityArticleAdapter", "onItemClick: " + view + " : " + section);
                if (view.getId() == R.id.ll_community_type) {
                    Intent intent = new Intent(getApplicationContext(), ArticleViewActivity.class);
                    intent.putExtra("articleId", articleVo.getId());
                    startActivity(intent);

                } else if (view.getId() == R.id.ll_comment) {
                    btnBottomDialog = new BtnBottomDialog(getApplicationContext(), articleVo.getId());
                    btnBottomDialog.show(getSupportFragmentManager(), "tag");

                } else if (view.getId() == R.id.iv_portrait) {
                    startActivity(new Intent(getApplicationContext(), PersonalHomepageActivity.class)
                            .putExtra("userId", articleVo.getUserID()));

                } else if (view.getId() == R.id.ll_like) {
                    personalHomepagePresenter.updateArticleLikeNum(getToken(getApplicationContext()), articleVo.getId(), 1);
                }

            }

            @Override
            public void onItemLongClick(View view, int section) {
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void getLikeMeLikeYouVisitPublish(Map<String, Integer> res) {
        this.binding.tvPublishNum.setText(res.get("publishNum").toString());
        this.binding.tvLikeMeNum.setText(res.get("likeMeNum").toString());
        this.binding.tvLikeYouNum.setText(res.get("likeYouNum").toString());
        this.binding.tvVisitNum.setText(res.get("visitNum").toString());
    }

    @Override
    public void updateArticleSuccess(String msg) {
        personalHomepagePresenter.getUserInfoById(this.getToken(this.getApplicationContext()), userId);
        personalHomepagePresenter.getLikeMeLikeYouVisitPublish(userId);
        personalHomepagePresenter.getArticle(token, userId, this.page, this.size);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (personalHomepagePresenter != null) {
            personalHomepagePresenter.getUserInfoById(this.getToken(this.getApplicationContext()), userId);
            personalHomepagePresenter.getLikeMeLikeYouVisitPublish(userId);
            personalHomepagePresenter.getArticle(token, userId, this.page, this.size);
        }
    }
}